<template>
  <div class="new-page table-h-48">
    <a-form-model layout="inline" :model="search" class="comm-search-f" :style="`width: calc(100% - ${sideMenuWidth} - 33px)`">

      <!-- 筛选条件与查询 -->
      <!-- 故障码 -->
      <a-form-model-item label="">
        <a-input
          v-model="search.keyword"
          placeholder="关键字"
        >
          <a-icon slot="suffix" :component="require('@/assets/icon/search.svg')" @click="changeTable({ current: 1 })" />
        </a-input>
      </a-form-model-item>
      <!-- 故障码 -->

      <!-- 是否发送邮邮件或sms -->
      <a-form-model-item style="flex-basis:18%!important">
        <a-button type="default" ghost :loading="userAirplanRelationLoading" @click="resetSearchHandler">
          重置
        </a-button>

      </a-form-model-item>
    </a-form-model>

    <div class="pt-16 pl-16 pr-16 pb-16">
      <a-button type="primary" ghost :loading="false" @click="addVisible=true">
        新增
      </a-button>

    </div>
    <a-table

      :columns="columns"
      size="middle"
      :data-source="userAirplanRelation"
      :row-key="(row,index) => row.id"
      :pagination="{
        showTotal:(total)=> `共 ${total} 条数据`,
        showSizeChanger: true,//设置每页显示数据条数
        showQuickJumper: true,
        size:'big',
        current:paginationOptions.pageNum,
        pageSize:paginationOptions.pageSize,
        total:paginationOptions.total
      }"
      :loading="userAirplanRelationLoading"
      @change="changeTable"
    />

    <!-- add -->
    <a-modal
      v-model="addVisible"
      :mask-closable="false"
      title=""
      :confirm-loading="addLoading"
      :width="400"
      class="rt-i-modal"
      :dialog-style="{height:'400px'}"
      centered
      @ok="confirmHandler"
      @cancel="cancelHandler"
    >
      <span slot="closeIcon" class="c-dialog-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>

      <div class="c-dialog-title fw-500">新增</div>
      <a-form-model
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        layout="horizontal"
      >
        <a-form-model-item label="用户名" prop="username">
          <a-select
            v-model="addForm.username"
            style="minWidth: 100%"
            class="input-type-o"
            show-arrow
            placeholder="用户名"
            @change="changeUserName"
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="selectItem in userList" :key="selectItem.id" :value="selectItem.username">
              {{ selectItem.username }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="机号" prop="tailnumber">
          <!-- <a-select

            mode="multiple"

          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="selectItem in ftmAirplaneList" :key="selectItem.id" :value="selectItem.tailnumber">
              {{ selectItem.tailnumber }}
            </a-select-option>
          </a-select> -->
          <a-select
            v-model="addForm.tailnumber"
            class="input-type-o input-type-o-nd"
            default-value="lucy"
            style="minWidth: 100%"
            placeholder="机号"
            :max-tag-count="3"
            show-arrow
            mode="multiple"
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-opt-group v-for="item in tailNumberAndFleet" :key="item.fleet" :label="item.fleet">
              <a-select-option
                v-for="itemTn in (item.tailNumber||[])"
                :key="item.fleet+itemTn"
                :disabled="userHasTailNumber.includes(item.fleet+'_'+itemTn)"
                :value="item.fleet+'_'+itemTn"
              >
                {{ itemTn }}
              </a-select-option>
            </a-select-opt-group>
          </a-select>
        </a-form-model-item>
        <!-- <a-form-model-item label="机队" prop="fleet">
          <a-select
            v-model="addForm.fleet"
            style="minWidth: 100%"
            class="input-type-o"
            show-arrow
            placeholder="机队"
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="selectItem in ftmFleetList" :key="selectItem.id" :value="selectItem.name">
              {{ selectItem.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item> -->
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { mapActions, mapGetters, mapState, mapMutations } from 'vuex';
export default {
  data() {
    return {
      addForm: {},
      addRules: Object.freeze({
        username: [
          { required: true, message: '请填写', trigger: 'change' }
        ],
        tailnumber: [
          { required: true, type: 'array', message: '请选择', trigger: 'change' }
        ],
        fleet: [
          { required: true, message: '请选择', trigger: 'change' }
        ]

      }),
      userHasTailNumber: [],
      addVisible: false,
      search: {},
      columns: Object.freeze([
        {
          title: '用户名',
          align: 'left',
          dataIndex: 'username',
          customRender: (value, record) => {
            return value || '--';
          }
        },
        {
          title: '机号',
          align: 'left',
          dataIndex: 'tailnumber',
          customRender: (value, record) => {
            return value;
          }
        },
        {
          title: '操作',
          align: 'left',
          dataIndex: 'option',
          width: 180,
          customRender: (value, record, index) => {
            return [
              <a-popconfirm
                title='确认删除此项?'
                ok-type='danger'
                ok-text='确认'
                cancel-text='取消'
                onConfirm={() => this.delItemHandler(record.id)}
              >

                <a-button type='link'>删除</a-button>
              </a-popconfirm>

              // <a-button type='primary' size='small' ghost>版本管理</a-button>
            ];
          }
        }
        // {
        //   title: '机队',
        //   align: 'left',
        //   dataIndex: 'fleet',
        //   customRender: (value, record) => {
        //     return value || '--';
        //   }
        // }

      ])
    };
  },
  computed: {
    ...mapState('userAirplaneRelation', [
      'userAirplanRelation',
      'userAirplanRelationLoading',
      'paginationOptions',
      'addLoading',
      'tailNumberAndFleet',
      'tailNumberAndFleetUserName'
    ]),
    ...mapState('fraMonitoring', [
      'ftmAirplaneList',
      'ftmFleetList'
    ]),
    ...mapState('users', [
      'userList',
      'userListLoading'
    ]),
    ...mapGetters('setting', ['sideMenuWidth'])
  },
  mounted() {
    this.getUserList();
    this.changeTable({ current: 1 });
    this.getTailNumberAndFleet();
  },
  methods: {
    ...mapMutations('userAirplaneRelation', [
      'setState'
    ]),
    ...mapActions('userAirplaneRelation', [
      'getListUserAirplanRelation',
      'addlistUserAirplanRelation',
      'getTailNumberAndFleet',
      'dellistUserAirplanRelation'
    ]),
    ...mapActions('users', [
      'getListUser'
    ]),
    changeTable({ current, pageSize = 10 }) {
      this.setState({ key: 'paginationOptions', payload: { ...this.paginationOptions, pageNum: current, pageSize }});
      this.getListUserAirplanRelation(this.search);
    },
    cancelHandler() {
      this.addVisible = false;
      this.addForm = {};
      this.addTitle = '新增';
      this.$refs.addForm.resetFields();
    },
    getUserList() {
      this.getListUser({ pageNum: 1, pageSize: 9999 });
    },
    confirmHandler() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (this.addForm.id) {
            // this.updateRole(this.addForm).then((rep) => {
            //   if (rep) {
            //     this.cancelHandler();
            //     this.getData();
            //   }
            // });
          } else {
            const params = {
              username: this.addForm.username,
              tailNumberAndFleets: []
            };
            this.addForm.tailnumber.forEach(item => {
              const fleet = item.split('_');
              const fIndex = params.tailNumberAndFleets.findIndex(fItem => fItem.fleet === fleet[0]);
              if (fIndex > -1) {
                params.tailNumberAndFleets[fIndex].tailNumber.push(fleet[1]);
              } else {
                params.tailNumberAndFleets.push({
                  fleet: fleet[0],
                  tailNumber: [fleet[1]]
                });
              }
            });
            this.addlistUserAirplanRelation(params).then((rep) => {
              if (rep) {
                this.cancelHandler();
                this.changeTable({ current: 1 });
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    async changeUserName(v) {
      await this.getTailNumberAndFleet({ userName: v });
      const bb = [];
      for (const item of this.tailNumberAndFleetUserName) {
        for (const itemTn of item.tailNumber) {
          bb.push(`${item['fleet']}_${itemTn}`);
        }
      }
      this.$set(this.addForm, 'tailnumber', [...bb]);
      this.userHasTailNumber = [...bb];
    },
    // 重置
    resetSearchHandler() {
      this.search = {};
      this.changeTable({ current: 1 });
    },
    delItemHandler(id) {
      this.dellistUserAirplanRelation(id).then((rep) => {
        if (rep) {
          this.getListUserAirplanRelation(this.search);
        }
      });
    }
  }
};
</script>

<style>

</style>
